//! 区块链ID

use core::convert::TryInto;

use crate::{Id, IdKind, ID_LEN};
#[cfg(feature = "wasm")]
use wasm_bindgen::prelude::*;

#[cfg_attr(feature = "wasm", wasm_bindgen)]
#[derive(Debug, PartialEq)]
pub struct BlockchainId {
    sn: [u8; 32],
}
#[cfg_attr(feature = "wasm", wasm_bindgen)]
impl BlockchainId {
    pub const fn new(sn: [u8; 32]) -> Self {
        return BlockchainId { sn };
    }
    pub const fn id(&self) -> Id {
        let mut buf: [u8; ID_LEN] = [0; ID_LEN];
        buf[0] = 0xA0 | 31;
        let mut i = 0;
        while i < 32 {
            buf[i + 1] = self.sn[i];
            i += 1;
        }
        Id {
            len: 1 + 32,
            buf: buf,
        }
    }
    pub fn try_from(id: &Id) -> Option<BlockchainId> {
        if id.kind() != IdKind::Blockchain {
            return None;
        }
        if id.len() as u8 != 1 + 32 {
            return None;
        }
        return Some(BlockchainId {
            sn: id.buf[1..1 + 32].try_into().unwrap(),
        });
    }
}
